/*************************************************************************
	> File Name: server.cc
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/24 16:22
 ************************************************************************/

#include "HttpServer.hpp"
#include <memory>
#include <vector>
#include <fstream>
#include "Util.hpp"

const std::string root = "./wwwroot";
const std::string homepage = "/index.html";

static void Usage(const std::string& proc)
{
    std::cout << "\nUsage:" << proc << " port" << std::endl;
}

void HandleHttpRequest(Sock* sock)
{
    std::string buffer;
    if (!sock->Read(buffer)) {
        std::cout << "server read error" << std::endl;
        return ;
    }
    std::cout << buffer << std::endl;
    std::vector<std::string> vline;
    Util::cutString(buffer, "\n", &vline);

    std::vector<std::string> vblock;
    Util::cutString(vline[0], " ", &vblock);

    std::string file = vblock[1];
    std::string target = root;
    if ("/" == file) {
        file = homepage;
    }
    target += file;
    std::cout << "target:" << target << std::endl;

    std::string content;
    std::ifstream in(target);
    if (in.is_open()) {
        std::string line;
        while (std::getline(in, line)) {
            content += line;
        }
        in.close();
    }
    std::string HttpResponse;
    if (content.empty()) {
        HttpResponse = "HTTP/1.1  404 NotFound\r\n";
    } else {
        HttpResponse = "HTTP/1.1 200 OK\r\n";
    }
    HttpResponse += "\r\n";
    HttpResponse += content;
    std::cout << "content:" << content << std::endl;
    std::cout << "###### start ##########" << std::endl;
    for (const auto& e : vblock) {
        std::cout << "----------" << e << "\n" << std::endl;
    }
    std::cout << "###### end ##########" << std::endl;
    std::cout << HttpResponse << std::endl;
    sock->Write(HttpResponse);
}

int main(int argc, char *argv[])
{
    if (argc != 2) {
        Usage(argv[0]);
        exit(1);
    }
    uint16_t port = atoi(argv[1]);
    std::unique_ptr<HttpServer> server(new HttpServer(port, HandleHttpRequest));
    server->Start();
    return 0;
}


